package com.cc.demo.message;

import com.cc.demo.channel.TransactionMessageOutChannel;
import com.cc.demo.dto.TransactionMessage;
import com.cc.demo.feign.MessageCenterFeign;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
@RequiredArgsConstructor
@Slf4j
public class TransactionMessagePublisher {

    private final MessageCenterFeign messageCenterFeign;
    private final TransactionMessageOutChannel out;

    public void sendSyncTransactionMessage(TransactionMessage<?> transactionMessage, TransactionMessagePublishAdapter transactionMessagePublishAdapter) {
        try {
            //1. 预发送Message
            TransactionMessage<?> prepareMessage = messageCenterFeign.prepareMessage(transactionMessage);
            if (Objects.nonNull(prepareMessage.getId())) {
                transactionMessage.setId(prepareMessage.getId());
                //2. 预定发送成功之后执行业务(TODO 里面需要有事务)
                transactionMessagePublishAdapter.afterPreCommitMessage(transactionMessage);
                //3. 业务执行成功或失败通知独立消息模块
                out.confirm().send(MessageBuilder.withPayload(transactionMessage).build());
            } else {
                //TODO 作进一步的处理
                log.info("call message center failed");
            }
        } catch (Exception e) {
            // TODO 3. 业务执行成功或失败通知独立消息模块
            log.info("需要通知独立消息模块");
            throw new RuntimeException(e.getMessage());
        }

    }
}
